package com.petcommunity.servlet;

import com.petcommunity.dao.PetDAO;
import com.petcommunity.model.Pet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

@WebServlet("/pets")
public class PetServlet extends HttpServlet {

    private PetDAO petDAO = new PetDAO();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        List<Pet> pets = petDAO.getAllPets();
        request.setAttribute("pets", pets);
        request.getRequestDispatcher("pets.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码为 UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        try {


            Pet pet = new Pet();
            pet.setName(request.getParameter("name"));
            pet.setSpecies(request.getParameter("species"));
            pet.setBreed(request.getParameter("breed"));
            pet.setGender(request.getParameter("gender"));
            pet.setBirthDate(new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("birthDate")));
            pet.setOwnerId(Integer.parseInt(request.getParameter("ownerId")));


            petDAO.addPet(pet);
            response.sendRedirect("pets");
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("error.jsp");
        }
    }
}

